var h = {};
var system = {
    nomore:!0,
}
var vDom;//vue操作器
var notification = null;
//桌面推送
var webMessagePush = function(){}
$(function(){
    $.mediaPhone = function() {
        return ! /ifr/.test(document.body.className) && document.body.clientWidth <= ($.maxPhoneW || 720) && 0 < document.body.clientWidth
    };
    $.isPC = !navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
    // 判断是否是手机
    $.isPhone = h.phone || $.mediaPhone();
    //隐藏左侧栏
    // $.isPhone && !/phone/i.test(document.body.className) && (document.body.className += " phone");
    $.isAndroid = -1 < navigator.userAgent.indexOf("Android") || -1 < navigator.userAgent.indexOf("Adr");
    $.isiOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
    $.isWeChat = -1 < navigator.userAgent.indexOf("MicroMessenger");

    if(version != '1.0'){
        $('.version1_0').remove();
    }

    if (window.Notification) {
        // var button = document.getElementById('button'), text = document.getElementById('text');

         function popNotice() {

            console.log(notification,'popNotice')

            if (Notification.permission == "granted" ) {
                //关闭上一个提示
                if(notification){
                    notification.close();
                    notification = null;
                }
                notification = new Notification("云客服系统：", {
                    body: '您有新消息，请注意查看！',
                    icon:  document.domain+'/static/logo/im.jpg',
                });
                notification.onclick = function() {
                    console.log('拒绝授权')
                    // text.innerHTML = '小仙女璐璐于' + new Date().toTimeString().split(' ')[0] + '成功拉黑你！';
                    notification.close();
                    notification = null;
                };
            }
        };
        // Notification.requestPermission()
        // web 右下角 消息推送
        webMessagePush = function (){
            // console.log(Notification.permission,Notification.permission,'---Notification.permission')
            if (Notification.permission == "granted") {
                popNotice();
            } else if (Notification.permission != "denied") {
                Notification.requestPermission(function (permission) {
                    popNotice();
                });
            }
        }
    } else {
        console.log('浏览器不支持Notification')
    }

    // //显示 隐藏 表情

    //
    // //点击查看更多
    // $("#histStart").click(function() {
    //     system.nomore ? wa() : ia()
    // })
    //

    //全局注册自定义指令，用于判断当前图片是否能够加载成功，可以加载成功则赋值为img的src属性，否则使用默认图片
    Vue.directive('real-img', async function (el, binding) {//指令名称为：real-img
        let imgURL = binding.value;//获取图片地址
        if (imgURL) {
            let exist = await imageIsExist(imgURL);
            if (exist) {
                el.setAttribute('src', imgURL);
            }
        }
    })

    vDom = new Vue({
        el: '#app',
        data: {
            ws:null,
            myAuto:[],//操作播放消息提示音
            myAutoInx:0,//当前焦点
            serverError:'',//服务器错误信息
            flashModel:null,//窗口闪动
            title:'在线咨询',
            inputMsg:'',//当前输入内容

            //屏幕宽度
            screenWidth: document.body.clientWidth,

            //对话消息  顾客列表
            chatUserList:[
                //用户信息
                // {id:90,uuid:'2_2',role:1,nickname:'用户一',headimg:'/static/head/1.jpg',active:false,hasNewMsg:0,online:1},
                // {id:91,uuid:'1_1',role:2,nickname:'用户二',headimg:'/static/head/16.jpg',active:false,hasNewMsg:0,online:1},
                // {id:92,uuid:'1_1',role:1,nickname:'用户三',headimg:'/static/head/20.jpg',active:false,hasNewMsg:0,online:1},
            ],

            //对话消息 客服列表
            chatKefuList:[
                // {id:14,uuid:'1_1',role:2,nickname:'测试群聊',headimg:'',active:false,hasNewMsg:0,online:1},
            ],

            //当前登录的用户
            currentUser:userinfo,

            //当前聊天消息
            currentChatMsg:[],
            //跟谁聊天
            currentChatUser:null,
            currentChatUserIndex:-1,

            //所有人的聊天记录
            chatMsgList:[],

            //所有人的历史聊天记录
            chatHistsMsgList:[],

            chatHistPages:{},//历史消息 记录翻页

            //初始化聊天消息  from  发送人   to 接收人
            // chatMsg:[
            //     {from_user_id:1,from_user_nickname:'用户一',from_user_headimg:'/static/head/1.jpg',to_user_id:3,from_role:1,msg:'在吗，找你有事',datetime:'2021-5-1 10:12:01'},
            //     {from_user_id:1,from_user_nickname:'用户三',from_user_headimg:'/static/head/3.jpg',to_user_id:1,from_role:2,msg:'在的',datetime:'2021-5-1 10:12:01'},
            //     {from_user_id:1,from_user_nickname:'用户三',from_user_headimg:'/static/head/3.jpg',to_user_id:1,from_role:2,msg:'微信上找我吧',datetime:'2021-5-1 10:12:01'},
            //     {from_user_id:1,from_user_nickname:'用户一',from_user_headimg:'/static/head/1.jpg',to_user_id:3,from_role:1,msg:'晚上老地方见',datetime:'2021-5-1 10:12:01'},
            // ],


            commit_dis:[],//常用语

            //显示隐藏
            showDom:{
                emojiPnl:false,//表情
                quesPnl:false,//问题
                leftIndex:0, // 0 顾客列表  1 客服列表
                rightIndex:1,
                isPlay:true,// 是否播放mp3

                jiben:1,//基本信息
                fujia:0,//附加信息
                laifang:0,//来访信息

                showLeftBox:false,//是否显示左侧列表
                showRightBox:false,//是否显示右侧列表
            },
            isCtrlEnter:false,//发送是否阻塞
        },
        watch:{
            //切换聊天对象时  改变当前聊天消息
          currentChatUserIndex:function(newVal,oldVal){
              this.currentChatMsg = this.chatMsgList[newVal];
              //切换对象 首次加载历史记录
              this.histStartClick(null,1);
              setTimeout(()=>{
                  scrollTop();
              },100)
          },
            //聊天记录增加时，同步到当前聊天数据中
            chatMsgList(){
                this.currentChatMsg = this.chatMsgList[this.currentChatUserIndex];
                  setTimeout(()=>{
                      scrollTop();
                  },100)
            },
            screenWidth: {
                immediate:true,
                handler(newValue) {
                    // console.log(newValue,'宽度变化')
                }
            },
            newMsgNumber:function(newVal){
                newVal>0 ? this.flashModel.start() : this.flashModel.close();
            },
        },
        //用户创建时
        mounted(){
            //初始化聊天记录，模拟缓存
            this.chatMsgList = (new Array(this.chatUserList.length)).fill([]);

            //默认跟第一个人聊天
            if(this.chatUserList.length>0){
                this.checkUser(0);
                // this.currentChatUser = this.chatUserList[this.currentChatUserIndex]
                // this.currentChatUser.active = true
                // this.currentChatUser.hasNewMsg = 0
            }

            //初始化
            this.init();

            console.log('From：',this.currentUser.nickname,this.currentUser.id,this.currentUser)
        },
        //方法集
        methods: {
            init(){
                var that = this;
                //初始化 websocket
                this.ws = myWebSocket(document.domain,'9092');
                //播放提示音
                for(var i = 0;i<10;i++){
                    this.myAuto[i] =  document.getElementById('mp3_'+i);
                }

                // this.myAuto[1] =  document.getElementById('mp32');
                this.apiInit();

                this.flashModel = flash_title()


                //初始化获取历史聊天记录
                setTimeout(()=>{
                    this.histStartClick(null,1);
                },1000)

                //监听窗口变化
                window.addEventListener("resize", function() {
                    return (() => {
                        window.screenWidth= document.body.clientWidth;
                        that.screenWidth= window.screenWidth;
                    })();
                });
                //获取焦点
                this.$nextTick(function () {
                    document.getElementById("text").focus();
                })
            },
            //获取初始化数据
            apiInit(){
                var param = {
                    'ticket':ticket,
                };
                var _this = this
                $.post('/home/main/index',param,function(res){
                    if(res.code==1){
                        _this.commit_dis = res.data.commit_dis;
                    }
                })

            },
            //发送新消息
            submitMessage(){
                if(!this.inputMsg) return ;
                if(!this.currentChatUser){
                    layer.msg('请选择消息接收对象~');return;
                }

                var msg_data = this.get_msg_data(this.inputMsg);

                // console.log(msg_data,'---msg_data')
                //向html中 展示消息
                this._addMessage(msg_data,this.currentChatUserIndex);

                this.ws.send(msg_data);

                //清空输入框
                this.inputMsg = '';

                //如果是手机模式  更新按钮状态
                isPhone() && textKeyDown()


                //隐藏窗体
                this.showDom.quesPnl = false
                this.showDom.emojiPnl = false

                //再次获取焦点
                $('#text').focus();
            },
            //获取发送消息 数据格式
            get_msg_data(msg,notXss){
                var date = new Date(),currentTime = date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate()+' '+date.getHours()+':'+date.getMinutes();
                currentTime = formatMsgTime2(date.getTime());
                msg = notXss?mb(msg):filterXSS(mb(msg));
                msg = msg.replace(/[\n+]/g,"<br/>");
                msg = msg.replace("<br/><br/>","<br/>");
                var msg_data = {
                    type:'say',//发消息
                    from_user_id:this.currentUser.uuid,
                    from_user_nickname:this.currentUser.nickname,
                    from_user_headimg:this.currentUser.headimg,//发送人信息
                    from_role:this.currentUser.role,
                    msg:msg,
                    to_user_id:this.currentChatUser.uuid,
                    datetime:currentTime,
                    is_reda:1,// 1 未读 2 已读
                };
                return msg_data;
            },
            //收到新消息
            addMessage(msg_data){
                //播放mp3
                this.playMp3();

                var from_user_id = msg_data['from_user_id'];
                var ChatUserIndex = -1;
                if(from_user_id == 0){
                    //机器人 只发送消息给顾客
                    ChatUserIndex = this.currentChatUserIndex
                }else{
                    this.chatUserList.forEach((item,index)=>{
                        if(item.uuid == from_user_id)
                            ChatUserIndex = index
                    })
                }
                this._addMessage(msg_data,ChatUserIndex);
                //发送web消息推送
                 webMessagePush();

            },
            //同步推送其他客户端的消息
            addMessage2(msg_data){
                var from_user_id = msg_data['to_user_id'];
                var ChatUserIndex = -1;
                if(from_user_id == 0){
                    //机器人 只发送消息给顾客
                    ChatUserIndex = this.currentChatUserIndex
                }else{
                    this.chatUserList.forEach((item,index)=>{
                        if(item.uuid == from_user_id)
                            ChatUserIndex = index
                    })
                }
                this._addMessage(msg_data,ChatUserIndex);
            },
            //实际发消息处理
            _addMessage(msg_data,ChatUserIndex){
                if(this.chatMsgList[ChatUserIndex] && this.chatMsgList[ChatUserIndex].length>0){
                    this.chatMsgList[ChatUserIndex].push(msg_data)
                }else{
                    this.$set(this.chatMsgList,ChatUserIndex,new Array(1).fill(msg_data))
                }
                // console.log('_addMessage',this.chatUserList,ChatUserIndex);
                //不是当前聊天窗口
                if(this.currentChatUserIndex != ChatUserIndex){
                    this.chatUserList[ChatUserIndex].hasNewMsg++;
                }
                //修改最后一条聊天记录
                this.chatUserList[ChatUserIndex].append.last = msg_data
            },
            //新增顾客用户
            addNewUser(info,isRole){
                isRole = isRole || false
                let isNew = true
                let index = -1;
                // 判断是 客服端  还是 顾客端
                var chatUserList =  this.chatUserList

                //客服 才拥有2个列表
                if(this.currentUser.role == 1){
                    chatUserList = info.role==2 ? this.chatUserList : this.chatKefuList
                }
                // console.log(info.uuid,info.online,chatUserList,isRole,info.role,'----info')
                chatUserList.forEach((item,inx)=> {
                    // console.log(item.uuid , info.uuid,'item.uuid == info.uuid')
                    if(item.uuid == info.uuid){
                        // item = info
                        isNew = false
                        item.online = info.online || 0
                        item.hasNewMsg = info.hasNewMsg || 0
                        item.append = {...info.append}
                        index = inx;
                        if(inx == this.currentChatUserIndex){
                            this.currentChatUser = item
                        }
                    }
                })
                if(isNew){
                    info.active = false;
                    info.hasNewMsg = info.hasNewMsg|| 0;
                    info.online =  info.online || 0;//在线状态
                    if(chatUserList.length==0){
                        info.active = true;
                    }
                    chatUserList.push(info);
                    index = chatUserList.length-1

                    //只有一个用户 默认选择第一个
                    if(index==0){
                        this.checkUser(index);
                    }
                }
                return index;
            },
            //切换当前聊天对象[客服]
            updataChatUser(chatUser){
                // chatUser.hasNewMsg = 0
                var index = this.addNewUser(chatUser);
                this.checkUser(index);
                // this.currentChatUserIndex = index
                // this.currentChatUser = this.chatUserList[index]
                // console.log('To：',this.currentChatUser.nickname+'['+this.currentChatUser.uuid+']',chatUser.nickname+'['+chatUser.uuid+']')
            },
            //用户上线or下线
            Upline(data){
                var chatUserList = this.chatUserList;
                //如果是客服 则拥有2个会话列表
                if(this.currentUser.role == 1){
                     chatUserList = data.role==2 ? this.chatUserList : this.chatKefuList
                }
                chatUserList.forEach((item,inx)=>{
                    // console.log(item,'--我的列表')
                    if(item.uuid == data.uuid){
                        item.online = data.online;
                        return;
                    }
                })
            },
            //选择顾客
            checkUser(index){
                //没有用户
                if(this.chatUserList.length==0) return false;
                //移除当前聊天用户的点燃事件
                if(this.chatUserList[this.currentChatUserIndex]) this.chatUserList[this.currentChatUserIndex].active = false;

                //清理标识
                if(this.chatUserList[index].hasNewMsg){
                    this.clearIsReda(this.chatUserList[index],this.currentUser);
                }

                //消除 未读
                this.chatUserList[index].hasNewMsg = 0;
                this.chatUserList[index].active = true;
                // console.log('选择顾客，并清理');
                this.currentChatUserIndex = index;
                this.currentChatUser = this.chatUserList[index];

                //如果显示了左侧用户列表 则 隐藏
                this.hideLeftRight()
            },
            //清理未读标识
            clearIsReda(currentChatUser,currentUser){
                if(!currentChatUser || !currentChatUser.uuid)return;
                console.log('清理标识')
                var msg_data = {
                    type:'is_reda',//消息已读 更新消息状态
                    from_user_id:currentChatUser.uuid,
                    from_role:currentChatUser.role,
                    to_user_id:currentUser.uuid,
                };
                this.ws.send(msg_data);
            },
            // 消息阅读回显
            is_redaCallback(to_user_id){
                // 寻找id
                var index = -1
                this.chatUserList.forEach((item,inx)=>{
                    if(item.uuid == to_user_id){
                        index = inx
                        return ;
                    }
                })
                    if(index==-1) return ;

                    //修改历史聊天记录
                this.chatHistsMsgList[index] && this.chatHistsMsgList[index].forEach(item=>{
                        item.is_reda = 2;
                    })
                //修改当前聊天记录
                this.chatMsgList[index] && this.chatMsgList[index].forEach(item=>{
                    item.is_reda = 2;
                })
            },
            //播放消息
            playMp3(){
                if(this.showDom.isPlay) {
                    var inx = this.myAutoInx
                    console.log(inx,'--播放音频')
                    this.myAuto[inx].play();
                    this.myAutoInx++
                    if(this.myAutoInx>=this.myAuto.length){
                        this.myAutoInx = 0;
                    }
                }
            },
            //点击事件
            // //显示 隐藏 表情
            emojiBtnClick(){
                drawEmoji();
                this.showDom.emojiPnl = !this.showDom.emojiPnl
                if(this.showDom.emojiPnl){
                    this.showDom.quesPnl = false
                }
            },
            //选择某个表情
            emojiPnlClick(a){
                a = a || window;
                a = a.target || a.srcElement;
                if(a !== $("#emojiPnl")[0]){
                    a = $.attr(a, "key")
                    this.inputMsg+=a;
                }
            },
            //更新手机号
            upMobileClick(){
                var params = {
                    id:this.currentChatUser.uuid,
                    newMobile:this.currentChatUser.mobile
                }
                // console.log(params)
                $.post('/home/main/upMobile',params,function(res){
                    if(res.code==1){

                        layer.msg(res.msg,{icon:1})

                    }else{
                        layer.msg(res.msg,{icon:5})
                    }
                })
            },
            //右侧 切换显示隐藏
            switchInfo(type){
                this.showDom[type] =!this.showDom[type]
            },
            //输入框获取焦点
            textFocus(){
                //隐藏表情框
                this.showDom.emojiPnl = false
                this.showDom.quesPnl = false

                this.clearIsReda(this.currentChatUser,this.currentUser)
            },

            //按下回车  直接发送消息
            textKeydown2(){
                setTimeout(()=>{
                    if(this.isCtrlEnter){
                        this.isCtrlEnter = false
                    }else{
                        this.submitMessage();//发送消息
                    }
                },100)
            },
            //输入换行
            textKeydown(){
                this.isCtrlEnter = true
                let tx = document.getElementById('text')
                let pos = cursorPosition.get(tx)
                cursorPosition.add(tx,pos,"\n");
                this.inputMsg = tx.value;
                // debounce(textKeyDown,100)()
            },
            //点击菜单按钮
            menuBtnClick(){
                clickMenu();
            },
            //点击转人工
            humanBtnClick(){
                this.inputMsg = '人工'
                this.submitMessage()
                this.playMp3();
                // sandBtn('人工');
            },
            //常见问题
            quesBtnClick(){
                this.showDom.quesPnl = !this.showDom.quesPnl
                if(this.showDom.quesPnl){
                    this.showDom.emojiPnl = false
                }
            },
            //选择常见问题
            quesClick(a){
                a = a || window;
                a = a.target || a.srcElement;
                if(a !== $("#emojiPnl")[0]){
                    var text = $(a).html()
                    $("#text").val($("#text")[0].value + text)
                    // addText(text)
                }
            },
            //设置连接状态
            setConnect(errorMsg){
                this.serverError = errorMsg
            },
            //加载历史消息
            histStartClick(e,auto){
                if(!this.currentChatUser) return false;
                auto = auto || false
                if(!this.chatHistPages[this.currentChatUserIndex]){
                    this.chatHistPages[this.currentChatUserIndex] = 1;
                }
                //如果是切换用户 则 部自动加载
                if(auto && this.chatHistPages[this.currentChatUserIndex]>1){
                    return ;
                }
                //加载历史记录
                var param = {
                    'page':this.chatHistPages[this.currentChatUserIndex],
                    'to_user_id':this.currentChatUser.uuid,//对方id
                    'to_role':this.currentChatUser.role,
                    'from_user_id':this.currentUser.uuid,//我方id
                    'ticket':ticket,
                };
                var _this = this
                $.post('/home/main/getHistStart',param,function(res){
                    var msg_data = res.data.data
                    //过滤掉当前聊天记录中 已经有的数据
                    msg_data = msg_data.filter(item=>{
                        var res = true;
                        _this.currentChatMsg && _this.currentChatMsg.forEach(msg=>{
                            if(msg.uuid == item.uuid){
                                res = false
                            }
                        })
                        return res
                    })
                    //如果有数据
                    if(msg_data.length>0){
                        if(!_this.chatHistsMsgList[_this.currentChatUserIndex]){
                            _this.$set(_this.chatHistsMsgList,_this.currentChatUserIndex,msg_data)
                        }else{
                            msg_data.forEach(item=>{
                                _this.chatHistsMsgList[_this.currentChatUserIndex].unshift(item)
                            })
                        }
                        //首次才需要 滚动到底部
                        auto && setTimeout(()=>{
                            scrollTop();
                        },100)
                    }
                    _this.chatHistPages[_this.currentChatUserIndex]++;

                    if(res.data.current_page >= res.data.last_page){
                        //还有数据
                        //没有更多数据
                        notMessage();
                    }

                })

            },
            //点击上传文件
            uploadClick(accept){
                accept = accept || '*'
                $('#fileObj').attr('accept',accept)

                $('#fileObj').click();

            },
            //获取文件
            getFile(event){
                var file = event.target.files;
                var addArr = []
                var upUrl = 'Image'
                for(var i = 0;i<file.length;i++){
                    //    上传类型判断
                    var imgName = file[i].name;
                    var idx = imgName.lastIndexOf(".");
                    if (idx != -1){
                        var ext = imgName.substr(idx+1).toUpperCase();
                        ext = ext.toLowerCase();
                        // console.log(ext,ext.indexOf(ext),'---ext.indexOf([\'jpg\',\'png\',\'jpeg\',\'gif\'])')
                        //判断是图片 还是文件

                        if(['jpg','png','jpeg','gif'].indexOf(ext)!==-1){
                            //图片
                        }else{
                            //文件
                            upUrl = 'File';
                        }
                        //禁止上传脚本文件
                        if (ext!='php' && ext!='js'){
                            addArr.push(file[i]);
                        }
                    }else{

                    }
                }
                if(addArr.length>0){
                    this.submitAddFile(addArr,upUrl);
                }
                $('#fileObj').val('')
            },
            //提交上传文件
            submitAddFile(addArr,upUrl){
                upUrl = upUrl || 'Image'
                if(0 == addArr.length){
                    layer.msg('请选择要上传的文件',{icon:5});
                    return;
                }
                var formData = new FormData();
                formData.append('ticket',ticket)
                for(var i=0;i<addArr.length;i++){
                    formData.append('file',addArr[i]);
                }
                var title = upUrl == 'Image' ? '图片发送中...':'文件发送中...'

                var index = layer.msg(title, {
                    icon: 16
                    ,shade: 0.01,
                    time:10000,
                });
                var _this = this
                $.ajax({
                    url:'/home/Upload/'+upUrl,
                    type:'POST',
                    data:formData,
                    contentType:false,//如果是传图片则这俩项需要为false
                    processData:false,
                    success:function(e){
                        layer.close(index)
                        if(e.code==1){
                            var msg
                            //上传成功
                            if(upUrl == 'Image'){
                                msg = `<img class="msg-image" src="${e.data.picCover}" alt="${e.data.fileName}" onclick="showImg(this)"/>`;
                            }else{
                                //文件的呈现方式
                                msg = `<span class="curpoicol" data-file="${e.data.picCover}" data-file_name="${e.data.fileName}" onclick="showFile(this)">${e.data.fileName}<i class="layui-icon layui-icon-file"  ></i></span>`;
                            }

                            var msg_data = _this.get_msg_data(msg,true);
                            //向html中 展示消息
                            _this._addMessage(msg_data,_this.currentChatUserIndex);
                            _this.ws.send(msg_data);
                            setTimeout(()=>{
                                scrollTop();
                            },1500)
                        }else{
                            layer.msg(e.msg,{icon:5})
                        }
                        console.log(e);
                    }
                });
            },

            //点击查看 用户的基本信息
            showInfo(from_user_id){
                if(from_user_id!=this.currentUser.uuid){
                    this.showDom.showRightBox = !this.showDom.showRightBox;
                }
            },

            //隐藏左右俩侧列表
            hideLeftRight(){
                if(this.showDom.showLeftBox || this.showDom.showRightBox){
                    setTimeout(()=>{
                        this.showDom.showLeftBox = false
                        this.showDom.showRightBox = false
                    },50)
                }
            }
        },
        //计算属性
        computed:{
            //新消息总数
            newMsgNumber(){
                var hasNewMsg = 0
                for (var i in this.chatUserList){
                    var item = this.chatUserList[i]
                    if(item.hasNewMsg>0)hasNewMsg += item.hasNewMsg
                }
                return hasNewMsg
            }
        },
        filters:{
            toDate: function (value) {
                if (!value) return ''
                var time = new Date(value).getTime()
                return formatMsgTime(time)
            },
        }
    })
});


/**
 * cursorPosition Object
 */
var cursorPosition = {
    get: function (textarea) {
        var rangeData = { text: "", start: 0, end: 0 };
        if (textarea.setSelectionRange) { // W3C
            textarea.focus();
            rangeData.start = textarea.selectionStart;
            rangeData.end = textarea.selectionEnd;
            rangeData.text = (rangeData.start != rangeData.end) ? textarea.value.substring(rangeData.start, rangeData.end) : "";
        } else if (document.selection) { // IE
            textarea.focus();
            var i,
                oS = document.selection.createRange(),
                // Don't: oR = textarea.createTextRange()
                oR = document.body.createTextRange();
            oR.moveToElementText(textarea);

            rangeData.text = oS.text;
            rangeData.bookmark = oS.getBookmark();

            // object.moveStart(sUnit [, iCount])
            // Return Value: Integer that returns the number of units moved.
            for (i = 0; oR.compareEndPoints('StartToStart', oS) < 0 && oS.moveStart("character", -1) !== 0; i++) {
                // Why? You can alert(textarea.value.length)
                if (textarea.value.charAt(i) == '\r') {
                    i++;
                }
            }
            rangeData.start = i;
            rangeData.end = rangeData.text.length + rangeData.start;
        }

        return rangeData;
    },
    set: function (textarea, rangeData) {
        var oR, start, end;
        if (!rangeData) {
            alert("You must get cursor position first.")
        }
        textarea.focus();
        if (textarea.setSelectionRange) { // W3C
            textarea.setSelectionRange(rangeData.start, rangeData.end);
        } else if (textarea.createTextRange) { // IE
            oR = textarea.createTextRange();

            // Fixbug : ues moveToBookmark()
            // In IE, if cursor position at the end of textarea, the set function don't work
            if (textarea.value.length === rangeData.start) {
                //alert('hello')
                oR.collapse(false);
                oR.select();
            } else {
                oR.moveToBookmark(rangeData.bookmark);
                oR.select();
            }
        }
    },
    add: function (textarea, rangeData, text) {
        var oValue, nValue, oR, sR, nStart, nEnd, st;
        this.set(textarea, rangeData);

        if (textarea.setSelectionRange) { // W3C
            oValue = textarea.value;
            nValue = oValue.substring(0, rangeData.start) + text + oValue.substring(rangeData.end);
            nStart = nEnd = rangeData.start + text.length;
            st = textarea.scrollTop;
            textarea.value = nValue;
            // Fixbug:
            // After textarea.values = nValue, scrollTop value to 0
            if (textarea.scrollTop != st) {
                textarea.scrollTop = st;
            }
            textarea.setSelectionRange(nStart, nEnd);
        } else if (textarea.createTextRange) { // IE
            sR = document.selection.createRange();
            sR.text = text;
            sR.setEndPoint('StartToEnd', sR);
            sR.select();
        }
    }
}



//点击图片 查看大图
function showImg(obj){
    var src = $(obj).attr('src');
    var json = {
        "title": "图片预览", //相册标题
        "id": 123, //相册id
        "start": 0, //初始显示的图片序号，默认0
        "data": [   //相册包含的图片，数组格式
            {
                "alt": "",
                "pid": 666, //图片id
                "src": src, //原图地址
                "thumb": src //缩略图地址
            }
        ]
    }
    layer.photos({
        photos: json
        ,anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
        ,success: function() {
            //以鼠标位置为中心的图片滚动放大缩小
            $(document).on("mousewheel",".layui-layer-photos",function(ev){
                var oImg = this;
                var ev = event || window.event;//返回WheelEvent
                //ev.preventDefault();
                var delta = ev.detail ? ev.detail > 0 : ev.wheelDelta < 0;
                console.log(delta,ev.detail,ev.wheelDelta,'---delta')
                //  缩放宽度位置比例 = (鼠标所在位置  - 图片左边) / 图片宽度
                var ratioL = (ev.clientX - oImg.offsetLeft) / oImg.offsetWidth,
                    ratioT = (ev.clientY - oImg.offsetTop) / oImg.offsetHeight,
                    ratioDelta = !delta ? 1 + 0.1 : 1 - 0.1,
                    w = parseInt(oImg.offsetWidth * ratioDelta),
                    h = parseInt(oImg.offsetHeight * ratioDelta),
                    l = Math.round(ev.clientX - (w * ratioL)),
                    t = Math.round(ev.clientY - (h * ratioT));
                $(".layui-layer-photos").css({
                    width: w, height: h
                    ,left: l, top: t
                });
                $("#layui-layer-photos").css({width: w, height: h});
                $("#layui-layer-photos>img").css({width: w, height: h});
            });


            var sX, eX, sY, eY, scale, x1, x2, y1, y2, imgLeft, imgTop, imgWidth, imgHeight, one = false;

            //监听手指事件
            $(document).on("touchstart touchmove touchend",".layui-layer-photos",function(event){
                var oImg = this;

                var originalWidth = oImg.offsetWidth;
                var originalHeight = oImg.offsetHeight;
                var imgLeft = oImg.offsetLeft;
                var imgTop = oImg.offsetTop;

                var touch1 = event.originalEvent.targetTouches[0];  // 第一根手指touch事件
                var touch2 = event.originalEvent.targetTouches[1];  // 第二根手指touch事件
                var fingers = event.originalEvent.touches.length;  // 屏幕上手指数量

                // 手指放在屏幕上的时候
                if (event.type == 'touchstart') {
                    if (fingers == 2) {
                        // 放缩图片x轴初始
                        sX = Math.abs(touch1.pageX - touch2.pageX);
                        sY = Math.abs(touch1.pageY - touch2.pageY);
                        one = false;
                    } else {
                        x1 = touch1.pageX;
                        y1 = touch1.pageY;
                        one = true
                    }
                } else if (event.type == 'touchmove') {
                    // 手指移动过程
                    if (fingers == 2) {
                        // 放缩图片x轴
                        eX = Math.abs(touch1.pageX - touch2.pageX);
                        eY = Math.abs(touch1.pageY - touch2.pageY);
                        // 为了放缩更加便捷，取最大的绝对值
                        scale = Math.abs(eX - sX) > Math.abs(eY - sY) ? eX - sX : eY - sY;
                        var w = originalWidth + scale,
                            h = originalHeight + scale,
                            l = Math.round(imgLeft - (scale/2)),
                            t = Math.round(imgTop - (scale/2));

                        $(".layui-layer-photos").css({
                            width: w, height: h
                            ,left: l, top: t
                        });
                        $("#layui-layer-photos").css({width: w, height: h});
                        $("#layui-layer-photos>img").css({width: w, height: h});
                        // 重置放大信息
                        sX = eX;
                        sY = eY;

                    } else if (one) {
                        // 错位控制,放缩未结束不允许移动位置
                        x2 = touch1.pageX;
                        y2 = touch1.pageY;
                        $(oImg).css({
                            'top': imgTop + y2 - y1,
                            'left': imgLeft + x2 - x1
                        })
                        y1 = y2
                        x1 = x2
                    }
                } else if (event.type == 'touchend') {
                    // 放缩结束
                    // originalWidth = oImg.offsetWidth;
                    // originalHeight = oImg.offsetHeight;
                    // imgLeft = oImg.offsetLeft;
                    // imgTop = oImg.offsetTop;
                }


            })

                //绑定缩放
            // touchScale($('.layui-layer-phimg').children('img'), $('.layui-layer-phimg'))
        }
    });
}

//点击文件 下载文件
function showFile(obj){
    var src = $(obj).data('file');
    var file_name = $(obj).data('file_name');
    // var url = "https://view.officeapps.live.com/op/embed.aspx?src="+src;
    var url = "https://office.hnbjsj.com/?src="+src+"&file_name="+file_name;
    layer.open({
        type: 2,
        title: '文件查看'+(file_name!=''?' - '+file_name:''),
        shadeClose: true,
        // maxmin: true,// 最大化
        closeBtn: 0, //不显示关闭按钮
        shade: 0.8,
        area: ['90%', '90%'],
        content: url //iframe的url
    });
    // window.open(src)
}